#include "boardentry.h"

#include <cmath>

#include <QPainter>
#include <QMouseEvent>

#include "config.h"

BoardEntry::BoardEntry(uint8_t row, uint8_t col, Gobang* gobang, QWidget *parent) : QWidget(parent)
{
    this->row = row;
    this->col = col;
    this->gobang = gobang;
}

void BoardEntry::paintEvent(QPaintEvent *ev)
{
    int size = BOARD_SIZE;
    int len = ENTRY_LENGTH;
    int status = gobang->get_status(row, col);

    QWidget::paintEvent(ev);
    QPainter p(this);

    QPainterPath path;
    if (row != 0) {
        path.moveTo(len/2, len/2);
        path.lineTo(len/2, 0);
    }
    if (row != size - 1) {
        path.moveTo(len/2, len/2);
        path.lineTo(len/2, len);
    }
    if (col != 0) {
        path.moveTo(len/2, len/2);
        path.lineTo(0, len/2);
    }
    if (col != size - 1) {
        path.moveTo(len/2, len/2);
        path.lineTo(len, len/2);
    }
    p.drawPath(path);

    if (status != -1) {
        const int offset = 5;
        path.clear();
        path.moveTo(len-offset, len/2);
        path.arcTo(offset, offset, len-offset, len-offset, 0, 360);
        QRadialGradient gradient(50, 50, 50, 50, 50);
        if (status == 1) {
            gradient.setColorAt(0, QColor(100, 100, 100));
            gradient.setColorAt(1, QColor(250, 250, 250));
        } else {
            gradient.setColorAt(1, QColor(10, 10, 10));
            gradient.setColorAt(0, QColor(150, 150, 150));
        }
        QBrush brush(gradient);
        brush.setStyle(Qt::RadialGradientPattern);
        p.fillPath(path, brush);
    }
}

void BoardEntry::mousePressEvent(QMouseEvent* ev) {
    QWidget::mousePressEvent(ev);
    if (gobang->place(row, col) == -1) {
        return;
    }
    if (gobang->get_winner() != -1) {
        emit game_over(gobang->get_winner(), "Five In a Row");
    }
}
